package com.joyxy.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 屏幕截图工具类
 */
public class ScreenCapture {
    private static final Logger logger = LoggerFactory.getLogger(ScreenCapture.class);
    
    private final Robot robot;
    
    public ScreenCapture() throws AWTException {
        this.robot = new Robot();
        logger.info("屏幕截图工具初始化完成");
    }
    
    /**
     * 截取指定区域的屏幕
     */
    public BufferedImage capture(Rectangle area) {
        try {
            return robot.createScreenCapture(area);
        } catch (Exception e) {
            logger.error("截图失败", e);
            return null;
        }
    }
    
    /**
     * 截取整个屏幕
     */
    public BufferedImage captureFullScreen() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRect = new Rectangle(screenSize);
        return capture(screenRect);
    }
    
    /**
     * 截图并保存到文件
     */
    public BufferedImage captureAndSave(Rectangle area, Path outputPath) throws IOException {
        BufferedImage image = capture(area);
        if (image != null) {
            // 确保目录存在
            Files.createDirectories(outputPath.getParent());
            
            // 保存图片
            ImageIO.write(image, "PNG", outputPath.toFile());
            logger.debug("截图已保存: {}", outputPath);
        }
        return image;
    }
    
    /**
     * 获取屏幕尺寸
     */
    public Dimension getScreenSize() {
        return Toolkit.getDefaultToolkit().getScreenSize();
    }
} 